package com.ttbj.product.api.impl;

import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import com.ttbj.constant.PayConfig;
import com.ttbj.constant.order.PayEnum;
import com.ttbj.core.util.DateUtils;
import com.ttbj.payment.component.PaymentService;
import com.ttbj.product.api.OrderFacade;
import com.ttbj.product.api.OwnerFacade;
import com.ttbj.product.api.PayFacade;
import com.ttbj.product.bean.dto.OrderDto;
import com.ttbj.product.bean.dto.PassiveScanQRCodeDataDto;
import com.ttbj.product.bean.dto.ViewData;
import com.ttbj.util.ViewModelUtil;
import com.ttbj.yitongpay.service.ScanQRCodeService;

@Service("payFacade")
public class PayFacadeImpl implements PayFacade  {

	@Autowired
	private OwnerFacade ownerFacade = null;

	@Autowired
	private PaymentService paymentService = null;

	@Autowired
	private OrderFacade orderFacde = null;

	@Autowired
	ScanQRCodeService scanQRCodeService = null;

	 
	public ViewData appletPay(String rootPath, OrderDto orderDto, Float amount, String openId) throws Exception {
		//预支付
		Map<String, String> map = paymentService.prePay(rootPath + PayConfig.APPLET_NOTIFY_URL, amount, orderDto.getOrderNum(), openId, String.valueOf(orderDto.getOrderId()));
		if (null == map || 0 <= map.size()) {
			return ViewModelUtil.buildFailure(99999, "订单生成失败：原因支付问题"); 
		}
		return ViewModelUtil.buildSuccess("成功", map);
	}

	public OrderDto appletNotify(String orderNum, String openId, String longFre, PassiveScanQRCodeDataDto data) throws Exception {
		/* 分账 */
		/* 被扫支付后的异步回调处理方法 */
		this.scanQRCodeService.passiveCallBackFunction(data);
		Map<String, String> transactionQuery = this.scanQRCodeService.transactionQuery(data.getMerOrderNum(), data.getTranDateTime(), 2);
		String attach = transactionQuery.get("attach");
		Long orderId = Long.valueOf(attach);
		/* 修改订单支付状态 */
		OrderDto orderDto = orderFacde.queryOrder(orderId);
		orderDto.setOrderPayWay(PayEnum.WX.getWay());
		orderDto.setOrderPayTime(DateUtils.getCurDttStr());
		orderDto.setOrderPayState(0);
		orderDto.setOrderId(orderId);
		orderFacde.updateOrder(orderDto);
		return orderDto;
	}

	@Override
	public ViewData appPay(String rootPath, OrderDto orderDto, Float amount, String openId) {
		
		return null;
	}

	@Override
	public OrderDto appNotify(String orderNum, String openId, String longFre, Long id) {
		// TODO Auto-generated method stub
		return null;
	}

}
